/*
 * @Author: zhangfeng
 * @Date: 2022-09-06 16:02:42
 * @LastEditTime: 2024-01-23 16:00:20
 * @LastEditors: zhangfeng
 * @Description:
 * @FilePath: \nodeapi\src\app\index.js
 * © 2023 张峰，All rights reserved.
 */
const path = require("path");
const { mimetype } = require("../config/uploadfile.config");
const fs = require("fs");
const Koa = require("koa");
const KoaBody = require("koa-body");
const KoaStatic = require("koa-static");
const Koaparameter = require("koa-parameter");
const {
  getUploadDirName,
  checkDirExist,
  getUploadFileExt,
  getUploadFileName,
} = require("../utils/index");
const router = require("../router/index");
// const userRouter =  require("../router/user.router.js")
// const goodsRouter =  require("../router/goods.router")

const errHandler = require("./errorHadnler");

const app = new Koa();
const myctx = {};
// 注册中间件
app.use(
  KoaBody({
    multipart: true,
    // encoding: "gzip",
    formidable: {
      uploadDir: path.join(__dirname, "../upload"),
      // 是否保留文件的后缀
      keepExtensions: true,
      // filter: (file) => {
      //   return file.mimetype && mimetype.includes(file.mimetype);
      // },
    },
    parsedMethods: ["POST", "GET", "PATCH", "PUT", "DELETE"],
  })
);

app.use(async (ctx, next) => {
  if (ctx.request.files && ctx.request.files.file) {
    const file = ctx.request.files.file;
    const pattern = /^\/([^/]+)/;
    const matchResult = ctx.request.url.match(pattern);
    // 获取文件的分类，可以根据自己的需求进行分类逻辑的实现
    const category = matchResult && matchResult[1] ? matchResult[1] : "other";

    // 创建分类文件夹
    const categoryDir = path.join(__dirname, `../upload/${category}`);
    try {
      if (!fs.existsSync(categoryDir)) {
        fs.mkdirSync(categoryDir);
      }
      // 将文件移动到分类文件夹中
      const filePath = path.join(categoryDir, file.newFilename);
      fs.renameSync(file.filepath, filePath);
      // 更新文件路径为分类后的路径
      file.path = filePath;
    } catch (error) {
      console.error(error);
    }
  }
  await next();
});

const staticPath = path.join(__dirname, "../upload");

app.use(KoaStatic(path.join(__dirname, "../upload"), { prefix: "/static" }));
app.use(Koaparameter(app));
app.use(router.routes());

// 统一的错误处理
app.on("error", errHandler);

module.exports = app;
